﻿"""
Definition of views.
"""
from django.shortcuts import render
from django.http import HttpRequest,HttpResponse,HttpResponseRedirect,JsonResponse
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.utils import timezone
from django.core import serializers
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.conf import settings
from django.core.mail import send_mass_mail
from django.core.mail import send_mail
from django.db.models import Sum
from django.db import connection

from .models import Message
from .models import Vacation
from django.template import RequestContext
from datetime import datetime
import json
import sys

default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)  
    sys.setdefaultencoding(default_encoding)

def index(request):
    #context={"messages":Message.objects.order_by('-publish_date')}
    #return render(request,'online/index.html')
    username=request.session.get('username')
    if username :
      return render(request,'online/index.html')
    else :
      return render(request,'online/login.html')
def home(request):
      return render(request,'online/home.html')

def rule(request):
    #context={"messages":Message.objects.order_by('-publish_date')}
    #return render(request,'online/rule.html')
    username=request.session.get('username')
    if username :
      return render(request,'online/rule.html')
    else :
      return render(request,'online/login.html')
def login(request):
    return render(request,'online/login.html')
def vacation(request):
    #context={"messages":Message.objects.order_by('-publish_date')}
    #return render(request,'online/vacation.html')
    username=request.session.get('username')
    if username :
      return render(request,'online/vacation.html')
    else :
      return render(request,'online/login.html')

def addvacation(request):
    #context={"messages":Message.objects.order_by('-publish_date')}
    return render(request,'online/addvacation.html')

def create(request):
    return render(request,'online/create.html')

@csrf_exempt
def save(request):
  usernames = request.POST.get('username','')
  titles = request.POST.get('title','')
  contentss = request.POST.get('content','')
  if usernames and titles and contentss:
   obj = Message(username=usernames,title=titles,contents=contentss,publish_date=timezone.now())
   obj.save()
   return HttpResponseRedirect('/online/index')
  else :
     context={'username':usernames,'title':titles,'content':contentss,'error':'title is empty !'}
     return render(request,'online/create.html',context)

@csrf_exempt
def savevacation(request):
  vac_date = request.POST.get('vac_date','')
  vac_person = request.POST.get('vac_person','')
  vac_interval = request.POST.get('vac_interval','')
  vac_type = request.POST.get('vac_type','')
  vac_reason = request.POST.get('vac_reason','')
  vac_enddate =request.POST.get('vac_enddate','')
  vac_week =''
  vac_approver ='Mime Li'
  vac_approvedate =timezone.now()
  vac_approvestatus =1
  vac_adddate =timezone.now()
  vac_temp =request.POST.get('vac_office','')
  vac_remark =''

  if vac_date and vac_person and vac_interval:
   obj = Vacation(vac_date=vac_date,vac_person=vac_person,vac_interval=vac_interval,vac_type=vac_type,vac_reason=vac_reason,vac_enddate=vac_enddate,vac_week=vac_week,vac_approver=vac_approver,vac_approvedate=vac_approvedate,vac_approvestatus=vac_approvestatus,vac_adddate=vac_adddate,vac_temp=vac_temp,vac_remark=vac_remark)
   obj.save()
   context={'success':'1','error':'0'}
   return HttpResponse(json.dumps(context), content_type='application/json')
   #return JsonResponse(context)
   #return HttpResponseRedirect('/online/vacation')
  else :
     context={'success':'0','error':'1'}
     return JsonResponse(context)
     #return HttpResponse(vac_date)

def dict(request):
    name_dict = {'twz': 'Love python and Django', 'zqxt': 'I am teaching Django'}
    return JsonResponse(name_dict)
	
def list(request):
    json_data = serializers.serialize("json", Message.objects.all(),ensure_ascii = False)
    return HttpResponse(json_data,content_type="application/json")
 
def getuserlist(request):
    userlist=settings.USER_LIST
    return HttpResponse(json.dumps(userlist),content_type='application/json')

@csrf_exempt
def sendmail(request):
    try:
        contenttitle = request.POST.get('contenttitle','')
        content = request.POST.get('content','')
        #msg='<a href="哈哈哈" target="_blank">点击激活</a>'
        send_mail('优办公管理信息系统',contenttitle,settings.DEFAULT_FROM_EMAIL,settings.ADMIN_USER_LIST,html_message=content)
        #send_mail('from vacation system',content,settings.DEFAULT_FROM_EMAIL,settings.ADMIN_USER_LIST,fail_silently=False)
        #send_mail('from vacation system',content,settings.DEFAULT_FROM_EMAIL,['kun.li@lixiaotech.com','dongwu.bie@lixiaotech.com','jason.mao@lixiaotech.com'],fail_silently=False)
       #send_mail('Subject here', 'Here is the message.',settings.DEFAULT_FROM_EMAIL,'249474612@qq.com', fail_silently=False)
      #message1 = ('Subject here', 'Here is the message', '249474612@qq.com', ['249474612@qq.com', '249474612@qq.com'])
      #message2 = ('Another Subject', 'Here is another message', '249474612@qq.com', ['249474612@qq.com'])
      #send_mass_mail((message1, message2), fail_silently=False)
    except Exception as e:
        return HttpResponse(json.dumps({'success':'0','error':'1','exception':str(Exception),'exception2':str(e),}),content_type='application/json')
    return HttpResponse(json.dumps({'success':'1','error':'0'}),content_type='application/json')

def page(deploy_list ,limit,offset):
    try:
        paginator = Paginator(deploy_list, limit)
    except Exception:
        return {"data":'none',"response_data":'none'}
    page = int(int(offset) / int(limit) + 1)
    data=paginator.page(page)
    response_data = {'total': deploy_list.count(), 'rows': []}
    return {"data":data,"response_data":response_data}

def listvacation(request):    
    data_set = []
    length = len(Vacation.objects.all())
    paginator = Paginator(Vacation.objects.all().order_by("-id").values(), 200)
    page = int(int(0) / int(1) + 1)
    data=paginator.page(page)
    for asset in data:
        data_set.append({ "vac_date":asset["vac_date"],"vac_person":asset["vac_person"],"vac_interval":asset["vac_interval"],"vac_type":asset["vac_type"],"vac_reason":asset["vac_reason"],"vac_enddate":asset["vac_enddate"],"vac_temp":asset["vac_temp"]})
    return HttpResponse(json.dumps({'rows':data_set,'total':length}),content_type='application/json')

@csrf_exempt
def vacationsum_(request):    
    data_set = []
    data = Vacation.objects.values("vac_person").annotate(tj=Sum("vac_interval")).order_by()
    #data = Vacation.objects.raw("select vac_person,id,sum(vac_interval) as tj from online_vacation group by vac_person,id")
    for asset in data:
        data_set.append({ "vac_person":asset["vac_person"],"tj":asset["tj"]})
    return HttpResponse(json.dumps(data_set),content_type='application/json')

@csrf_exempt
def vacationsum(request):    
    cursor = connection.cursor()
    cursor.execute('select u.username vac_person,ifnull(sum(v.vac_interval),0) tj from online_user u left join online_vacation v on u.username=v.vac_person group by u.username')
    #raw = cursor.fetchone()
    rawData=cursor.fetchall()
    col_names = [desc[0] for desc in cursor.description]
    data_set = []
    result = []
    for row in rawData:
            objDict = {}
            for index, value in enumerate(row):
                objDict[col_names[index]] = value
            result.append(objDict)
            data_set.append({ "vac_person":objDict["vac_person"],"tj":objDict["tj"]})

    #for asset in result:
        #data_set.append({ "vac_person":asset["vac_person"]})
    return HttpResponse(json.dumps(data_set,ensure_ascii=False),content_type='application/json,charset=utf-8')

@csrf_exempt
def vacationsumyear(request):
    year = request.POST.get('year','')
    cursor = connection.cursor()
    #cursor.execute('select u.username vac_person,ifnull(sum(v.vac_interval),0) tj from online_user u left join online_vacation v on u.username=v.vac_person where v.vac_adddate like "'+year+'%" group by u.username ORDER BY tj DESC')
    cursor.execute('select username from online_user')
    #raw = cursor.fetchone()
    rawData=cursor.fetchall()
    col_names = [desc[0] for desc in cursor.description]
    data_set = []
    result = []
    for row in rawData:
            objDict = {}
            for index, value in enumerate(row):
                objDict[col_names[index]] = value
                cursor.execute('select ifnull(sum(vac_interval),0) from online_vacation where vac_person="'+objDict["username"]+'" and vac_adddate LIKE "'+year+'%"')
                raw = cursor.fetchone()
                data_set.append({ "vac_person":objDict["username"],"tj":raw[0]})
                   #result.append(objDict)
    #for asset in result:
        #data_set.append({ "vac_person":asset["vac_person"]})
    return HttpResponse(json.dumps(data_set,ensure_ascii=False),content_type='application/json,charset=utf-8')

    #return HttpResponse(json.dumps({'rows':data_set}),content_type='application/json')

    #return  HttpResponse(json.dumps(J_data["response_data"]))

    #for asset in Vacation.objects.all().values():

    #data_set.append(asset.getAttrs())
#J_data['response_data']['model'].append({ "vac_date":asset["vac_date"],"vac_person":asset["vac_person"],"vac_interval":asset["vac_interval"],"vac_reason":asset["vac_reason"],"vac_enddate":asset["vac_enddate"],"vac_temp":asset["vac_temp"]})

#J_data=page(Vacation.objects.all().values(),request.GET.get("limit"),request.GET.get("offset"))

    #resp = {'errorcode': 100, 'detail': 'Get success'}
    #return HttpResponse(json.dumps(resp), content_type="application/json")
	
	#data = models.Message.objects.values('username', 'title', 'contents', 'publish_date')
    #data = serializers.serialize("json", tomcats)
    #return JsonResponse(list(data), safe=False)